// stock/warehouse_update/warehouse_update.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tableName: '仓库定义',
    fieldList: [
      {field_id: 'warehouse_id', label: '仓库编码',type: 'text',is_null: false}
      ,{field_id: 'warehouse_name', label: '仓库名称',type: 'text',is_null: false}
      ,{field_id: 'addr', label: '仓库地址',type: 'text',is_null: true}
      ,{field_id: 'mark', label: '备注',type: 'text',is_null: true}
    ],
    switchField:[
      {field_id: 'qiyongbiaoshi', label: '启用标识'},
      {field_id: 'is_default', label: '默认标识'},
    ],
    defData:{},
    formData:{
      warehouse_id: '',
      warehouse_name:'',
      addr:'',
      mark: '',
      qiyongbiaoshi: true,
      is_default: false
    },

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项


  },

  // 记录验证表单项
  validIpt(e) {
    let { validObj, } = this.data
    this.data.validObj = {
      ...validObj,
      ...e.detail,
    };
  },
  //启用标识
  toggleUsed(e) {
    let detail = e.detail,
      field = e.currentTarget.dataset.field,
      {formData} = this.data;
    formData[field] = detail;
    this.setData({formData});
  },

  //布局中字段修改
  bindChange(e){
    let detail = e.detail,
      field = detail.field,
      id = field.field_id || field.fieldName,
      type = field.type,
      val = detail.val,
      formData = this.data.formData;
    formData[id] = val;
  },

  //绑定提交
  bindSubmit(e){
    wx.showLoading({mask: true});
    let type = e.currentTarget.dataset.type;

    // 开启验证
    this.data.validObj = {};
    this.setData({
      validFlag: !this.data.validFlag,
    });
    let {validObj} = this.data;
    this.validForm(validObj).then(valid => {
      if(valid) { // 表单验证通过
        let {formData,tableName} = this.data;
        console.log('表单验证通过');
        let post = {
          "table":{
            "table_id":"Warehouse",
            "entitys":[
              {"entity": formData,"details":[]}
            ]}};
        wx.$post(3,'DynamicUpdate/dynamic_update_v3',post).then(res=>{
          if (res.errcode !=0)return;
          wx.$toast('保存成功！');
          this.refreshList(formData.row_id,this.data.editIndex)

          //关闭
          if (type === 'close'){
            wx.navigateBack({ //跳转到前一个页面
              delta:1,//前一个页面
            });
          }
          //清空
          if (type === 'clear'){
            formData = {is_used: true};
            tableName = '新增仓库';
          }
          //复制
          if (type === 'copy'){
            formData.row_id = 0;
            tableName = '复制仓库';
          }
          this.setData({
            formData,
            tableName
          });
        });

      } else {  // 表单验证不通过
        console.log('表单验证不通过');
        wx.$toast('必填项不能为空！')
      }
    })
  },

  //刷新列表
  refreshList(id,index){
    const pages = getCurrentPages();//获取页面栈
    const beforePage = pages[pages.length - 2];  //前一个页面
    beforePage.refreshData(id,index);
  },

  //验证数据
  validForm(validObj){
    return new Promise((resolve, reject) => {
      let valid = Object.values(validObj).includes(false) ? false : true;
      resolve(valid)
    })
  },

  ready(options){
    let {rowid,status,edit_index} = options,
      tableName = '新增仓库',
      obj = {};
    if (status === 'edit'){
      tableName = '编辑仓库'
    }
    if (status === 'copy'){
      tableName = '复制商品'
    }
    obj = {tableName};
    if (edit_index !== undefined)obj.editIndex = edit_index;
    this.setData(obj);

    if (rowid){
      this.getData(rowid).then(row=>{
        let data= row[0] && row[0].entity[0],
          {formData} = this.data;
        wx.$each(formData,(key,val)=>{
          formData[key] = data[key];
        });
        if (status === 'copy'){
          formData.row_id = 0;
        } else {
          formData.row_id = data.row_id;
          formData.is_used = data.is_used;
        }
        this.setData({formData})

      })
    }
  },

  getData(rid){
    return new Promise(resolve => {
      wx.$post(3,'DynamicQuery/query_dynamic_v2',{table_id: "Warehouse", row_id: rid}).then(res=>{
        if (res.errcode != 0)return;
        let data = res.data.row || [];
        resolve(data);
      })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.$setBarTitle();
    this.ready(options);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
